package manager


import protocol.BaseProtocol
import serialport.MDBPortManager

object PayManager {

    var isPay = false
        private set

    var isError = false
        private set

    var webPayFlag = false
        private set

    var webPayCallbackFunc = { ret: Boolean -> }
        private set

    fun onPay() {
        isPay = true
        isError = false
        if (webPayFlag) {
            webPayCallbackFunc(true)
        }
        webPayFlag = false
    }

    fun onExit() {
        if (isPay) {
            return
        }
        if (isError) {
            return
        }
        cancel()
    }

    fun onError() {
        isError = true
        isPay = false
        if (webPayFlag) {
            webPayCallbackFunc(false)
        }
        webPayFlag = false
    }

    fun cancel() {
        val bytes = BaseProtocol(0x13).appendByte(0x01).build()
        MDBPortManager.write(bytes)

        val bytes2 = BaseProtocol(0x13).appendByte(0x04).build()
        MDBPortManager.write(bytes2)
    }

    fun payInWeb(price: Double, callback: (Boolean)-> Unit) {
        isPay = false
        isError = false
        webPayFlag = true
        webPayCallbackFunc = callback
        val priceUnit = (price * 100).toInt()
        val bytes = BaseProtocol(0x13).appendByte(0x00).appendInt2(priceUnit).build()
        MDBPortManager.write(bytes)
    }

    fun request() {
        isPay = false
        isError = false
        webPayFlag = false
        val info = WaresManager.selectInfo()
        val price = (info.wares.price * 100).toInt()
        val bytes = BaseProtocol(0x13).appendByte(0x00).appendInt2(price).build()
        MDBPortManager.write(bytes)
    }

    fun success() {
        val bytes = BaseProtocol(0x13).appendByte(0x02).build()
        MDBPortManager.write(bytes)

        val bytes2 = BaseProtocol(0x13).appendByte(0x04).build()
        MDBPortManager.write(bytes2)

        webPayFlag = false
    }

    fun refund() {
        val bytes = BaseProtocol(0x13).appendByte(0x03).build()
        MDBPortManager.write(bytes)

        val bytes2 = BaseProtocol(0x13).appendByte(0x04).build()
        MDBPortManager.write(bytes2)

        webPayFlag = false
    }
}


